package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 检查项服务
 */
@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService {
    //注入DAO对对象
    @Autowired
    private CheckItemDao checkItemDao;

    //添加检查项
    @Override
    public void add(CheckItem checkItem) {
        checkItemDao.add(checkItem);
    }

    //检查项分页查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckItem> page = checkItemDao.selsectByCondition(queryString);

        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());

        return result;
    }

    //根据ID删除检查项
    @Override
    public void deleteById(Integer id) {
        //不能直接删除，需要判断当前检查项是否和检查组关联，如果已经和检查组进行了关联则不允许 删除
        //判断当前检查项是否关联到检查组
        long count = checkItemDao.findCountByCheckItemId(id);
        if (count>0){
            //此时检查项关联到检查组，不允许删除
            throw new RuntimeException();
        }else {
            checkItemDao.deleteById(id);
        }
    }

    //编辑检验项目
    @Override
    public void edit(CheckItem checkItem) {
        checkItemDao.edit(checkItem);
    }

    //根据id查询
    @Override
    public CheckItem findById(Integer id) {
        return checkItemDao.findById(id);
    }

    //查询所有
    @Override
    public List<CheckItem> findAll() {
        return checkItemDao.findAll();
    }


}
